//
//  CKSegmentBar.m
//  CKPagerComponent
//
//  Created by mac on 2017/5/1.
//  Copyright © 2017年 corkiios. All rights reserved.
//

typedef void(^doneBlock)(NSInteger index);
#import "CKSegmentBar.h"

static CGFloat const CKSegmentBarMargin = 16;

@interface CKSegmentBar()
{
    UIButton *_lastBtn;
}
@property (nonatomic, strong) UIScrollView *contentView;
@property (nonatomic, strong) NSMutableArray <UIButton *>*itemBtns;
@property (nonatomic, strong) UIImageView *indicatorView;
@property (nonatomic, strong) CKSegmentBarConfig *config;
@property (nonatomic, copy)doneBlock done;

@property (nonatomic,assign)NSInteger currentIndex;

@property (nonatomic,assign)CGPoint lastContentViewContentOffset;



@end

@implementation CKSegmentBar

+ (instancetype)segmentBarWithFrame:(CGRect)frame {
    
    CKSegmentBar *segmentBar = [[CKSegmentBar alloc] initWithFrame:frame];
    UIScrollView *contentView = [[UIScrollView alloc] init];
    contentView.showsHorizontalScrollIndicator = NO;
    contentView.showsVerticalScrollIndicator = NO;
    contentView.scrollsToTop = NO;
    [segmentBar addSubview:contentView];
    segmentBar.contentView = contentView;
    segmentBar.backgroundColor = RGBA(20, 26, 40, 1);
   
    return segmentBar;
}

- (void)setItems:(NSArray<NSString *> *)items {
    
    _items = items;
    
    [self.itemBtns enumerateObjectsUsingBlock:^(UIButton * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
        [obj removeFromSuperview];
    }];
    
    self.itemBtns = nil;
    
    for (NSString *title in items) {
        
        UIButton *btn = [UIButton buttonWithType:UIButtonTypeCustom];
        btn.tag = self.itemBtns.count;
        [btn sizeToFit];
        [btn setTitle:title forState:UIControlStateNormal];
        [btn setTitleColor:C153 forState:UIControlStateNormal];
        [btn setTitleColor:RGBA(247, 84, 112, 1) forState:UIControlStateSelected];
        [btn addTarget:self action:@selector(btnAction:) forControlEvents:UIControlEventTouchUpInside];
        btn.titleLabel.font = font(14);
        [self.itemBtns addObject:btn];
        [self.contentView addSubview:btn];
    }
    _lastBtn = self.itemBtns.count > 0?  self.itemBtns[0] : nil;
    _lastBtn.selected = YES;
    
    [self setNeedsLayout];//标记需要重新布局
    [self layoutIfNeeded];
    
}

- (void)setSelectedIndex:(NSInteger)selectedIndex {
    
    _selectedIndex = selectedIndex;
    [self btnAction:self.itemBtns[selectedIndex]];
}

- (void)didSelectedCompleteBlock:(void (^)(NSInteger index))completeBlock{
    if (completeBlock) {
        self.done = ^(NSInteger index) {
            completeBlock(index);
        };
    }
    
}

- (void)setContentScrollView:(UIScrollView *)contentScrollView{
    if (_contentScrollView != nil) {
        [_contentScrollView removeObserver:self forKeyPath:@"contentOffset"];
    }
    _contentScrollView = contentScrollView;
    self.contentScrollView.scrollsToTop = NO;
    [self.contentScrollView addObserver:self forKeyPath:@"contentOffset" options:NSKeyValueObservingOptionNew context:nil];
}
- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary<NSKeyValueChangeKey,id> *)change context:(void *)context {
    if ([keyPath isEqualToString:@"contentOffset"]) {
        CGPoint contentOffset = [change[NSKeyValueChangeNewKey] CGPointValue];
    
        if ((self.contentScrollView.isTracking || self.contentScrollView.isDecelerating)) {
           
            CGFloat ratio = contentOffset.x/self.contentScrollView.bounds.size.width;
            NSInteger baseIndex = floorf(ratio);
            CGFloat remainderRatio = ratio - baseIndex;
        
            if (remainderRatio == 0) {
                if (!(self.lastContentViewContentOffset.x == contentOffset.x && self.currentIndex == baseIndex)) {
                    [self updateSegmentBarWithCurrentIndex:baseIndex];
                    self.currentIndex = baseIndex;
                    self.done(baseIndex);
                }
            }
        }
        self.lastContentViewContentOffset = contentOffset;
    }
}
- (void)dealloc{
    if (self.contentScrollView) {
        [self.contentScrollView removeObserver:self forKeyPath:@"contentOffset"];
    }
}


- (void)updateSegmentBarWithCurrentIndex:(NSInteger)index{
    UIButton *currentBtn = self.itemBtns[index];
    
    [self setNeedsLayout];//标记需要重新布局
    [self layoutIfNeeded];
    if (_lastBtn == currentBtn) return;
    _lastBtn.selected = NO;
    currentBtn.selected = YES;
    _lastBtn = currentBtn;
    [UIView animateWithDuration:0.1 animations:^{
        self.indicatorView.width = currentBtn.width + 24;
        self.indicatorView.center = currentBtn.center;
    }];
    CGFloat scrollx = currentBtn.centerX - self.contentView.width * 0.5;
    if (scrollx < 0) {
        scrollx = 0;
    }
    if (scrollx > self.contentView.contentSize.width - self.contentView.width) {
        scrollx = self.contentView.contentSize.width - self.contentView.width;
    }
    [self.contentView setContentOffset:CGPointMake(scrollx, 0) animated:YES];
}


- (void)btnAction:(UIButton *)sender {
    
    
    self.currentIndex = sender.tag;
        
    [self setNeedsLayout];//标记需要重新布局
    [self layoutIfNeeded];
    
    
    if (_lastBtn == sender) return;
    
    _lastBtn.selected = NO;
    sender.selected = YES;

    _lastBtn = sender;
    
    [UIView animateWithDuration:0.1 animations:^{
        
        self.indicatorView.width = sender.width + 24;
        self.indicatorView.center = sender.center;
    }];
    
    CGFloat scrollx = sender.centerX - self.contentView.width * 0.5;
    
    if (scrollx < 0) {
        scrollx = 0;
    }
    if (scrollx > self.contentView.contentSize.width - self.contentView.width) {
        scrollx = self.contentView.contentSize.width - self.contentView.width;
    }
    
    [self.contentView setContentOffset:CGPointMake(scrollx, 0) animated:YES];
    
    self.done(sender.tag);
    
}

- (void)layoutSubviews {
    
    [super layoutSubviews];
    self.contentView.frame = self.bounds;
    CGFloat totalBtnWidth = 0;
    
    for (UIButton *btn in self.itemBtns) {
        
        [btn sizeToFit];
        totalBtnWidth += btn.width;
    }
    
    CGFloat margin = (self.width - totalBtnWidth) / (self.itemBtns.count + 1);
    
    if (margin < CKSegmentBarMargin) {
        
        margin = CKSegmentBarMargin;
    }
    
    CGFloat x = margin;
    int count = 0;
    for (UIButton *btn in self.itemBtns) {
        if (count == 1 && margin == CKSegmentBarMargin) {
            margin = 28.0f;
            x+=12;
        }
        btn.cl_x = x;
        btn.centerY = self.height / 2;
        x += btn.width + margin;
        count++;
    }
    
    self.indicatorView.width = _lastBtn.width + 24;
    self.indicatorView.center = _lastBtn.center;
   

    [self.contentView setContentSize:CGSizeMake(x, 0)];
}

- (UIImageView *)indicatorView {
    
    if (_indicatorView == nil) {
        UIImage *image = [UIImage imageNamed:@"home_recommend_tag"];
        image = [image stretchableImageWithLeftCapWidth:floorf(image.size.width/2) topCapHeight:floorf(image.size.height/2)];
        
        _indicatorView = [[UIImageView alloc] initWithImage:image];
        [self.contentView addSubview:_indicatorView];
    }
    return _indicatorView;
}

- (NSMutableArray *)itemBtns {
    
    if (_itemBtns == nil) {
        
        _itemBtns = [NSMutableArray array];
    }
    
    return _itemBtns;
}

- (CKSegmentBarConfig *)config {
    
    if (_config == nil) {
        
        _config = [CKSegmentBarConfig defultCongfig];
    }
    
    return _config;
}
@end
